package cn.virens.common.project.generator.enums;


import cn.virens.common.util.exception.APIException;
import cn.virens.common.util.exception.ExceptionUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.text.StrUtil;

import java.io.File;

public class EnumScanToExcelUtil {
    protected static final String root = System.getProperty("user.dir");

    protected static final String tpl = """
            package cn.virens.provider.easyexcel_PACKAGE0_;
            
            import cn.virens.common.easyexcel.dict.AbstractExcelDictConverter;
            import cn.virens.common.easyexcel.dict.ExcelDict;
            import cn.virens.common.easyexcel.dict.ExcelDictBuilder;
            import cn.virens.common.util.exception.APIException;
            
            import _PACKAGE1_._NAME_;
            
            public class ExcelDictWith_NAME_ extends AbstractExcelDictConverter<Integer> {
            
            	/** 生成构建工具 */
            	public static ExcelDict builder(String... headName) throws APIException {
            		ExcelDictBuilder<_NAME_> builder = builder0(headName);
            		builder.setClazz(ExcelDictWith_NAME_.class);
            		builder.setValueFun(_NAME_::getKey);
            		builder.setKeyFun(_NAME_::getDesc);
            
            		return builder.build(_NAME_.values());
            	}
            
            }
            """;

    public static void generator(String out, String... pkgs) throws APIException {
        EnumScan.scanPackage(pkgs).forEach(c -> ExceptionUtil.safe0(() -> {
            String ctx = StrUtil.replace(tpl, "_NAME_", c.getSimpleName());
            ctx = StrUtil.replace(ctx, "_PACKAGE1_", c.getPackageName());
            ctx = StrUtil.replace(ctx, "_PACKAGE0_", getPath(c, pkgs));

            FileUtil.writeUtf8String(ctx, getFile(c, out, pkgs));
        }));
    }

    /**
     * 获取相对包路径
     */
    private static String getPath(Class<?> clazz, String[] pkgs) {
        String p = clazz.getPackageName();

        for (int i = 0; i < pkgs.length; i++) {
            p = StrUtil.replace(p, pkgs[i], "");
        }

        return p;
    }

    /**
     * 获取保存路径
     */
    private static File getFile(Class<?> clazz, String out, String[] pkgs) {
        String p = FileUtil.normalize(root + out + getPath(clazz, pkgs));
        String n = clazz.getSimpleName();

        p = StrUtil.replace(p, ".", "/");
        p = p + "/ExcelDictWith";
        p = p + n + ".java";

        return FileUtil.file(p);
    }

}